package com.cgycms.webdeploy.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName : DownUtil
 * @Description : 下载工具类
 * @Author : 王力超
 * @Date: 2020-11-10 11:17
 */
public class DownUtil {


    /**
     * 返回错误信息
     *
     * @param response 响应
     * @param msg      错误信息
     */
    public static void responseError(HttpServletResponse response, String msg) {
        response.setCharacterEncoding("utf-8");
        response.setStatus(200);
        response.setContentType("application/json; charset=UTF-8");
        try {
            response.getWriter().print(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * http文件下载
     *
     * @param path     路径
     * @param response 响应
     */
    public static void download(String path, HttpServletResponse response) {
        try {
            String name = FileUtil.getName(path);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(name.getBytes("GB2312"), "8859_1"));
            InputStream inputStream = new FileInputStream(path);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                out.write(b, 0, length);
            }
            out.flush();
            out.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String delPath = path.substring(0, path.lastIndexOf(File.separator));
            FileUtil.del(delPath);
        }

    }


    /**
     * 创建临时目录
     *
     * @param sysTmp
     * @return
     */
    public static String mkdir(String sysTmp) {
        if (!sysTmp.endsWith("/")) {
            sysTmp += File.separator;
        }
        String tmp = sysTmp + IdUtil.simpleUUID() + File.separator;
        FileUtil.mkdir(tmp);
        return tmp;
    }

}
